package cn.edu.suda.catalina.service.implement;

import cn.edu.suda.catalina.bean.AppInfo;
import cn.edu.suda.catalina.service.IndexService;
import cn.edu.suda.catalina.utils.SessionUtils;
import cn.edu.suda.catalina.utils.TraversalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * Created by long on 16-11-28.
 */
@Service
public class IndexServiceImpl implements IndexService{

    @Autowired
    private AppInfo appInfo;

    private SessionUtils sessionUtils;

    @Override
    public void upload(String path, MultipartFile apkFile) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        File appDir = new File(path);
        if (!appDir.exists()) {
            if (!appDir.mkdirs()) {
                return;
            }
        }
        String fileName = apkFile.getOriginalFilename(); //获取文件名
        String extensionName = fileName.substring(fileName.lastIndexOf(".")); //获取后缀名
        String newFileName = System.currentTimeMillis() + extensionName; //新文件名
        File serverFile = new File(appDir.getAbsolutePath() + File.separator + newFileName);
        try {
            inputStream = apkFile.getInputStream();
            outputStream = new FileOutputStream(serverFile);
            int len = 0;
            byte[] bytes = new byte[1024]; //字节流
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            inputStream.close();
            outputStream.close();

            appInfo.setAppPath(path);
            appInfo.setAppName(newFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void selectAndroid(String path) {
        sessionUtils = new SessionUtils(appInfo.getAppPath(), appInfo.getAppName(), appInfo.getAppPackage(), appInfo.getAppActivity());
        String pathname = path + "screen.png";
        sessionUtils.Screenshot(pathname);
        sessionUtils.tearDown();
    }

    @Override
    public void start() {
        sessionUtils = new TraversalUtils(appInfo.getAppPath(), appInfo.getAppName(), appInfo.getAppPackage(), appInfo.getAppActivity());
        ((TraversalUtils) sessionUtils).traversal(appInfo.getAppPackage(), ".MainActivity");
        sessionUtils.tearDown();
    }
}
